package main

import (
	"flag"
	config2 "gitee.com/zylvcxq/gotham-utils/config"
	"gitee.com/zylvcxq/gotham-utils/env"
	"github.com/go-kratos/kratos/contrib/config/apollo/v2"
	zap2 "github.com/go-kratos/kratos/contrib/log/zap/v2"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/tx7do/kratos-transport/transport/rabbitmq"
	_ "go.uber.org/automaxprocs"
	"gotham-plan-manage/internal/conf"
	"gotham-plan-manage/internal/infra/cache/redis"
	"os"
)

// go build -ldflags "-X main.Version=x.y.z"
var (
	// Name is the name of the compiled software.
	Name string
	// Version is the version of the compiled software.
	Version string
	// flagconf is the config flag.
	flagconf string

	id, _ = os.Hostname()
)

const (
	APPName = "gotham-plan-manage"
)

func init() {
	flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func newApp(logger log.Logger, gs *grpc.Server, hs *http.Server, rs *rabbitmq.Server) *kratos.App {
	register := conf.InitEtcdRegister()

	return kratos.New(
		kratos.ID(id),
		kratos.Name(APPName),
		kratos.Version(Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.Server(
			gs,
			hs,
			rs,
		),
		kratos.Registrar(register), // 服务注册
	)
}

func main() {
	flag.Parse()
	// zap日志
	logger := log.With(zap2.NewLogger(conf.InitZapLogger()),
		"ts", log.DefaultTimestamp,
		"caller", log.DefaultCaller,
		"service.id", id,
		"service.name", Name,
		"service.version", Version,
		"trace.id", tracing.TraceID(),
		"span.id", tracing.SpanID(),
	)
	closeFunc, err := config2.InitConfig(&conf.GServer,
		apollo.WithAppID(APPName),
		apollo.WithCluster("DEV"),
		apollo.WithEndpoint(env.GetApolloServerURL()),
		apollo.WithNamespace("application"),
		apollo.WithSecret(env.GetApolloSecret()),
	)
	if err != nil {
		panic(err)
	}
	defer closeFunc()
	// 因为考虑到可能要全局使用redis，单独注册
	err = redis.NewRedisClient(conf.GServer.Data)
	if err != nil {
		panic(err)
	}
	err = conf.NewRabbitMQPublisher()
	if err != nil {
		panic(err)
	}
	// 指定消息队列
	app, cleanup, err := wireApp(conf.GServer.Server, conf.GServer.Data, logger)
	if err != nil {
		panic(err)
	}
	defer cleanup()
	// start and wait for stop signal
	if err := app.Run(); err != nil {
		panic(err)
	}
}
